package com.begye.smartloan.apptest.ext

import org.json.JSONArray
import org.json.JSONObject

fun JSONArray?.toJSONObjectList(): List<JSONObject> {
    val list = mutableListOf<JSONObject>()
    this?.let {
        for (index in 0 until it.length()) {
            val item = it.optJSONObject(index)
            if (item != null) {
                list.add(item)
            }
        }
    }
    return list
}

fun JSONArray?.toList(): List<Any> {
    val list = mutableListOf<Any>()
    this?.let {
        for (i in 0 until it.length()) {
            val value = it[i]
            list.add(
                when (value) {
                    is JSONObject -> value.toHaspMap() // 递归处理嵌套的JSONObject
                    is JSONArray -> value.toList() // 递归处理嵌套的JSONArray
                    else -> value // 其他类型的值直接使用
                }
            )
        }
    }
    return list
}

fun JSONObject?.toHaspMap(): HashMap<String, Any> {
    val map = HashMap<String, Any>()
    this?.let {
        val keys = it.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            val value = it[key]
            map[key] = when (value) {
                is JSONObject -> value.toHaspMap() // 递归处理嵌套的JSONObject
                is JSONArray -> value.toList() // 将JSONArray转换为List
                else -> value // 其他类型的值直接使用
            }
        }
    }

    return map
}